package com.aiti.lulian.controller;

import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.bo.YunZhanTingEnterpriseHistoryRequest;
import com.aiti.lulian.dto.EnterpriseSelectDto;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.entity.LuLianEnterpriseHistory;
import com.aiti.lulian.entity.LuLianEnterpriseUser;
import com.aiti.lulian.entity.request.LuLianEnterpriseRenZhengRequest;
import com.aiti.lulian.service.ILuLianEnterpriseService;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.service.ILulianEnterpriseHistoryService;
import com.aiti.lulian.vo.EnterpriseAuthVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 企业认证
 * @author sangguangcan
 */
@RestController
@RequestMapping("/history")
public class LulianEnterpriseHistoryController extends WebController {

    private ILuLianEnterpriseUserService enterpriseUserService;

    private ILuLianEnterpriseService luLianEnterpriseService;

    private ILulianEnterpriseHistoryService lulianEnterpriseHistoryService;

    public LulianEnterpriseHistoryController(ILulianEnterpriseHistoryService lulianEnterpriseHistoryService,ILuLianEnterpriseService luLianEnterpriseService,
                                             ILuLianEnterpriseUserService enterpriseUserService) {
        this.lulianEnterpriseHistoryService = lulianEnterpriseHistoryService;
        this.luLianEnterpriseService = luLianEnterpriseService;
        this.enterpriseUserService = enterpriseUserService;
    }

    /**
     * 云展厅企业认证
     * @param request
     */
    @PostMapping("/yunZhanTingEnterpriseHistory")
    public Message yunZhanTingEnterpriseHistory(@RequestBody YunZhanTingEnterpriseHistoryRequest request){
        String userId = findUserId();
        return lulianEnterpriseHistoryService.yunZhanTingEnterpriseHistory(request,userId);
    }

    /**
     * 云展厅企业认证回显
     */
    @GetMapping("yunZhanTingEnterpriseHistoryShow")
    public Message yunZhanTingEnterpriseHistoryShow(){
        String userId = findUserId();
        return lulianEnterpriseHistoryService.yunZhanTingEnterpriseHistoryShow(userId);
    }

    /**
     * 修改更新企业认证
     * @return
     */
    @PutMapping("/yunZhanTingUpdateEnterpriseHistory")
    public Message yunZhanTingUpdateEnterpriseHistory(@RequestBody YunZhanTingEnterpriseHistoryRequest request){
        return lulianEnterpriseHistoryService.yunZhanTingUpdateEnterpriseHistory(request,findUserId());
    }

    /**
     * 添加企业认证
     * @return
     */
    @PostMapping("/addEnterpriseHistory")
    public Message addEnterpriseHistory(@RequestBody LuLianEnterpriseRenZhengRequest request){
        String userId = "";
        if(StringUtils.isNotBlank(request.getUserId())){
            userId = request.getUserId();
        }else{
            userId = findUserId();
        }
        Message message = lulianEnterpriseHistoryService.addEnterpriseHistory(request, userId);
        if(message.getCode() == 1){
            System.out.println("----->" + message.getCode());
            System.out.println("----->" + message.getMsg());
            System.out.println("----->" + String.valueOf(message.getObj()));
        }else{
            System.out.println("----->" + "保存成功");
        }

        return message;
    }

    /**
     * 更新企业认证
     * @return
     */
    @PutMapping("/updateEnterpriseHistory")
    public Message updateEnterpriseHistory(@RequestBody LuLianEnterpriseRenZhengRequest request){
        return lulianEnterpriseHistoryService.updateEnterpriseHistory(request,findUserId());
    }

    @GetMapping("enterpriseHistoryShow")
    public Message enterpriseHistoryShow(){
        String userId = findUserId();
        System.out.println("------------:"+userId);
        return lulianEnterpriseHistoryService.enterpriseHistoryShow(userId);
    }

    @PostMapping("enterpriseCheck")
    public Message enterpriseCheck(@RequestBody Map<String,String> params){
        if(StringUtils.isBlank(params.get("baseId")) || StringUtils.isBlank(params.get("code"))){
            return Message.fail("没有找到BaseId或认证代码");
        }
        return lulianEnterpriseHistoryService.enterpriseCheck(params,findUserId());
    }

    @GetMapping("queryEnterHistoryList")
    public Message queryEnterHistoryList(@RequestParam EnterpriseSelectDto enterpriseSelectDto){

        try {
            Integer pageSize = enterpriseSelectDto.getPageSize();
            Integer pageNum = enterpriseSelectDto.getPageNum();
            Page<EnterpriseAuthVo> page = startPage(pageNum,pageSize);
            List<EnterpriseAuthVo> list=lulianEnterpriseHistoryService.queryEnterHistoryList(page,enterpriseSelectDto);
            return Success(getPageResult(list,pageNum,pageSize,(int)page.getTotal()));
        }catch (Exception e){
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    /**
     * @describe 根据用户ID查询其已认证的企业名称
     * @creator WongMz
     * @date 2024-09-03
     */
    @ApiOperation("根据用户ID查询其已认证的企业名称")
    @GetMapping("/queryEnterpriseName/{userId}")
    public Message queryEnterpriseNameByUserId(@PathVariable("userId") String userId){
        try {
        if (StrUtil.isBlank(userId)) {
            logger.error("查询异常：===》入参异常");
            return Fail("入参异常");
        }
        LambdaQueryWrapper<LuLianEnterpriseUser> enterpriseUserWrapper = new LambdaQueryWrapper<>();
        enterpriseUserWrapper.eq(LuLianEnterpriseUser::getUserId, userId);
        List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserService.list(enterpriseUserWrapper);
        List<String> enterpriseIds = enterpriseUserList.stream().map(LuLianEnterpriseUser::getEnterpriseId).collect(Collectors.toList());
        if (enterpriseIds == null || enterpriseIds.size() == 0) {
            enterpriseIds.add("0");
        }
        LambdaQueryWrapper<LuLianEnterpriseHistory> enterpriseHistoryWrapper = new LambdaQueryWrapper<>();
        enterpriseHistoryWrapper.in(LuLianEnterpriseHistory::getBaseId, enterpriseIds);
        int count = lulianEnterpriseHistoryService.count(enterpriseHistoryWrapper);
        if (count == 0) {
            return Fail("该账号未认证企业，请先进行企业认证！");
        } else if (count == 1 && enterpriseUserList.size() > 1) {
            return Fail("该账号的企业关联记录存在多条！");
        } else if (count > 1) {
            return Fail("该账号关联了多个认证企业！");
        }

        return Success(lulianEnterpriseHistoryService.queryEnterpriseIdAndName(userId));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    /**
     * @describe 条件查询已认证的企业列表
     * @creator WongMz
     * @date 2024-09-11
     */
    @ApiOperation("条件查询已认证的企业列表")
    @GetMapping("/list")
    public Message queryEnterpriseHistoryList(LuLianEnterpriseHistory luLianEnterpriseHistory){
        try {
            QueryWrapper<LuLianEnterprise> wrapper = new QueryWrapper<>();
            if (StrUtil.isNotEmpty(luLianEnterpriseHistory.getBaseName())) {
                wrapper.like("base_name", luLianEnterpriseHistory.getBaseName());
            }
            wrapper.eq("status","1");
            wrapper.last(" limit 5");
            return Success(luLianEnterpriseService.list(wrapper));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    @GetMapping("/queryUserEnterpriseCount")
    public Message queryUserEnterpriseCount(){
        try {
            String userId = findUserId();
            return Success(enterpriseUserService.selectEnterpriseCountByUserId(userId));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Fail(e.getMessage());
        }
    }
}